<?php

namespace App\Module\User\Service;

use App\Constants\Constant;
use App\Model\User;
use App\Model\UserCredential;
use App\Model\UserScore;
use App\Model\UserWechatInfo;
use Hyperf\DbConnection\Db;

class UserService {

    public function createByWechat($wechat_info){
        return Db::transaction(function() use($wechat_info){
            $user = new User();
            $user->setAttribute("username",$wechat_info['nickName']);
            $user->setAttribute("thumbnail",$wechat_info['avatarUrl']);
            $user->save();

            $user_score = new UserScore();
            $user_score->setAttribute("user_id",$user->user_id);
            $user_score->save();

            $user_wechat_info = new UserWechatInfo();
            $user_wechat_info->setAttribute("user_id",$user->user_id);
            $user_wechat_info->setAttribute("openid",$wechat_info['openId']);
            $user_wechat_info->setAttribute("avatar_url",$wechat_info['avatarUrl']);
            $user_wechat_info->setAttribute("country",$wechat_info['country']);
            $user_wechat_info->setAttribute("city",$wechat_info['city']);
            $user_wechat_info->setAttribute("gender",$wechat_info['gender']);
            $user_wechat_info->setAttribute("nickname",$wechat_info['nickName']);
            $user_wechat_info->setAttribute("province",$wechat_info['province']);
            $user_wechat_info->save();

            $user_credential = new UserCredential();
            $user_credential->setAttribute("user_id",$user->user_id);
            $user_credential->setAttribute("username",$wechat_info['openId']);
            $user_credential->setAttribute("type",Constant::WECHAT);
            $user_credential->save();
            return $user;
        });
    }

    public function getByCredential($credential,$type){
        $credential = UserCredential::query()->where([['username',$credential],['type',$type]])->first();
        return $credential ? $credential->user : null;
    }
}